import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

const CredentialImport = () => {
  const [credentialData, setCredentialData] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();

  // 从URL查询参数中检查是否有预填充的凭证数据
  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const prefillData = queryParams.get('prefill');
    
    if (prefillData) {
      try {
        // 解码并解析URL参数中的JSON数据
        const decodedData = decodeURIComponent(prefillData);
        const parsedData = JSON.parse(decodedData);
        
        // 格式化JSON数据以便显示
        setCredentialData(JSON.stringify(parsedData, null, 2));
      } catch (error) {
        console.error('解析预填充凭证数据失败:', error);
        setError('无法解析预填充的凭证数据');
      }
    }
  }, [location.search]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setSuccess(null);

    try {
      // 尝试解析用户输入的JSON
      let parsedCredential;
      try {
        parsedCredential = JSON.parse(credentialData);
      } catch (jsonError) {
        setError('无效的JSON格式，请检查输入内容');
        setLoading(false);
        return;
      }

      // 调用API导入凭证
      const response = await walletApi.importCredential(parsedCredential);
      
      if (response.success) {
        setSuccess(`凭证 ${response.credentialId} 导入成功！`);
        setCredentialData('');
        setTimeout(() => {
          navigate('/wallet/credentials');
        }, 2000);
      } else {
        setError(response.error || '导入凭证失败，请稍后再试');
      }
    } catch (error) {
      console.error('导入凭证时出错:', error);
      setError('导入凭证时发生错误，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const handleBackToList = () => {
    navigate('/wallet/credentials');
  };

  return (
    <div className="credential-import">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">导入凭证</h4>
        <button 
          className="btn btn-outline-secondary"
          onClick={handleBackToList}
        >
          <i className="bi bi-arrow-left me-2"></i>
          返回凭证列表
        </button>
      </div>

      {error && (
        <div className="alert alert-danger">
          <i className="bi bi-exclamation-triangle me-2"></i>
          {error}
        </div>
      )}

      {success && (
        <div className="alert alert-success">
          <i className="bi bi-check-circle me-2"></i>
          {success}
        </div>
      )}

      <div className="card mb-4">
        <div className="card-body">
          <h5 className="card-title mb-3">粘贴您的可验证凭证 (JSON格式)</h5>
          <p className="card-text text-muted mb-4">
            请粘贴您从发行方收到的完整可验证凭证JSON数据，例如从发行方API响应中复制的凭证对象。
          </p>

          <form onSubmit={handleSubmit}>
            <div className="mb-3">
              <textarea
                className="form-control code-editor"
                value={credentialData}
                onChange={(e) => setCredentialData(e.target.value)}
                rows="15"
                placeholder='{\n  "@context": ["https://www.w3.org/2018/credentials/v1"],\n  "id": "urn:uuid:...",\n  "type": ["VerifiableCredential"],\n  "issuer": "did:...",\n  ...\n}'
                required
              ></textarea>
            </div>

            <div className="d-grid">
              <button 
                type="submit" 
                className="btn btn-primary"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                    导入中...
                  </>
                ) : (
                  <>
                    <i className="bi bi-cloud-upload me-2"></i>
                    导入凭证
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>

      <div className="card">
        <div className="card-body">
          <h5 className="card-title">支持的凭证格式</h5>
          <p className="card-text">
            目前支持以下可验证凭证格式：
          </p>
          <ul className="list-group">
            <li className="list-group-item">
              <i className="bi bi-check-circle-fill text-success me-2"></i>
              W3C可验证凭证 (JSON-LD格式)
            </li>
            <li className="list-group-item">
              <i className="bi bi-check-circle-fill text-success me-2"></i>
              Polygon ID 凭证
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default CredentialImport; 